package com.xhj.arithmetic;
import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

/**
 * -
 *
 * @author 周沫
 * @Date 2021-07-17
 * @Time 1:06
 */
public class A0001 {

	public static void main(String[] args) {
		int[] nums = {2, 1, 34, 2, 3, 6, 4};
		int target = 4;
		int[] indexs = twoSum3(nums, target);

		System.out.print("nums: ");
		for (int i = 0; i < nums.length; i++) {
			System.out.print(nums[i] + ", ");
		}

		System.out.print("\nindexs: ");
		for (int i = 0; i < indexs.length; i++) {
			System.out.print(indexs[i] + ", ");
		}
		System.out.print("\nthe nums: ");
		for (int i = 0; i < indexs.length; i++) {
			System.out.print(nums[indexs[i]] + ", ");
		}
	}

	//暴力寻找
	public static int[] twoSum(int[] nums, int target) {
		for (int i = 0; i < nums.length - 1; i++) {
			for (int j = i + 1; j < nums.length; j++) {
				if (nums[i] + nums[j] == target) {
					return new int[]{i, j};
				}
			}
		}
		return null;
	}

	//两遍HashMap
	public static int[] twoSum2(int[] nums, int target) {
		Map<Integer, Integer> hashMap = new HashMap();
		for (int i = 0; i < nums.length; i++) {
			hashMap.put(nums[i], i);
		}
		System.out.println("hashMap: ");
		hashMap.forEach((k,v)->{
			System.out.println(k+": "+v);
		});
		for (int i = 0; i < nums.length; i++) {
			if (hashMap.containsKey(target - nums[i])) {
				return new int[]{i, hashMap.get(target-nums[i])};
			}
		}
		return null;
	}

	public static int[] twoSum3(int[] nums, int target) {
		Map<Integer, Integer> hashMap = new HashMap();
		for (int i = 0; i < nums.length; i++) {
			if (hashMap.containsKey(target - nums[i])) {
				return new int[]{hashMap.get(target - nums[i]), i};
			}
			hashMap.put(nums[i], i);
		}
		return null;
	}
}
